App.controller('mediaStopController', ['$rootScope', '$scope', '$state', 'Page', function ($rootScope, $scope, $state, Page) {
	
	Page.ajaxGetQuiet('media/stop/mediatypes.do', null, function (resp) {
        $scope.mediaTypes = resp.data;
    });
	
	Page.ajaxPostQuiet('anon/markType/tree.do', null, function (resp) {
        $scope.marks = resp.data;
    });
	
	$scope.mediaStopGrid = {
		options : {
			lazy : false,
			scrollX : true,
			fixedColumns: {
				rightColumns: 5,
				leftColumns : 0
			}
		},
		column_defs: [
				{
	            	target: 1,
	            	template: function(row){
	            		return '<a href="javascript:void(0)" ed-click="viewStopInfo">' + row.stopName + '</a>'
	            			+ '<a href="javascript:void(0);" ed-click="viewStopPosition" title="定位" class="icon-pointer" style="float:right;padding-right: 10px;font-size:13px;"></a>';
	            	}
	            },

				{
					target: 13,
					template: function(row){
						//if(row.zgEquipments == 0) {
						//	return '';
						//} else {
						//	return '<a href="javascript:void(0)" ed-click="viewZgEquipments">'+row.zgEquipments+'</a>'
						//}

						return '<a href="javascript:void(0)" ed-click="viewZgEquipments">'+row.zgEquipments+'</a>'
					}
				},
				{
					target: 14,
					template: function(row){
						//if(row.hctEquipments == 0) {
						//	return '';
						//} else {
						//	return '<a href="javascript:void(0)" ed-click="viewHctEquipments">'+row.hctEquipments+'</a>'
						//}
						return '<a href="javascript:void(0)" ed-click="viewHctEquipments">'+row.hctEquipments+'</a>'
					}
				},
				{
					target: 18,
					template: function(row){
						//if(row.zgEquipments == 0) {
						//	return '';
						//} else {
						//	return '<a href="javascript:void(0)" ed-click="viewZgEquipments">'+row.zgEquipments+'</a>'
						//}

						return '<a href="media/stop/dealQrCode.do?stopId=' + row.stopId  + '&stopNo=' + row.stopNo + '">下载 </a>'

					}
				},
	            {
	            	target: 19,
	            	buttons: [
	                    {
	                        name: '编辑',
	                        clazz: 'btn-edit',
	                        icon: 'fa-edit',
	                        event: function(row){
	                    		$scope.mediaStop = row;
								$scope.mediaStop.stopMarks = $scope.mediaStop.stopMarks || [];
								Page.ajaxGetQuiet('media/stop/' + $scope.mediaStop.stopId + '/marks.do', null, function (resp) {
							         $(resp.data).each(function(index, mark) {
							        	 $scope.mediaStop.stopMarks[index] = mark.markId;
							         });
							         $scope.stopMediaModal.show();
							    });
	                        }
	                    },
						//{
						//	name : '设备',
						//	clazz: 'btn-edit',
						//	icon : 'glyphicon glyphicon-paperclip',
						//	event : function(row) {
						//		$scope.equipmentGrid.query.stopId = row.stopId;
						//		$scope.equipmentGrid.query();
						//		$scope.equipmentModal.show();
						//	}
						//},
	                    {
	                        name: '媒体资源',
	                        clazz: 'btn-success',
	                        icon: 'fa-file-text-o',
	                        event: function(row){
	                    		$scope.mediaStop = row;
								Page.ajaxPostQuiet('media/stop/selectStopEquipments.do',{stopId : row.stopId},function(resp){
									$scope.stopEquipmentList = resp.data;
									$scope.stopResourcesModal.show();
								});

	                        }
	                    }
                    ]
	            }
		],
		viewZgEquipments : function(row) {

			$scope.zgEquipmentGrid.query.stopId = row.stopId;
			$scope.zgEquipmentGrid.query.queryType = "2"; //站杆

			$scope.zgEquipmentGrid.query();
			$scope.zgEquipmentModal.show();
		},
		viewHctEquipments : function(row) {
			$scope.hctEquipmentGrid.query.stopId = row.stopId;
			$scope.hctEquipmentGrid.query.queryType = "1"; //候车亭
			$scope.hctEquipmentGrid.query();
			$scope.hctEquipmentModal.show();
		},
		toAddMediaStop : function(){
			$scope.mediaStop = {};
			$scope.mediaStop.county = $scope.options.AREA_COUNTY[0].value;
			$scope.stopMediaModal.show();
		},
		viewStopInfo : function(row){
			$scope.stopMediaInfoModal.setStopId(row.stopId).show();
		},
		viewAllStopPosition : function(){
			 $scope.stopPointsModal.init(this.data).show();
		},
		viewStopPosition : function(row){
			 $scope.stopPointsModal.init(row).show();
		},
		viewStopMediaResource : function(row,elem){
			$scope.mediaStop = row;
			var mediaId = elem.attr('mediaId');
			$(this.stopMedias).each(function(index, media) {
				 if(mediaId == media.mediaId){
					 $scope.mediaStop.mediaType = media;
				 }
			});
    		$scope.stopMediaResourceModal.show();
		}
	};
	
	$scope.stopMediaModal = {
		onShow : function(){
			$scope.mediaStop = $scope.mediaStop || {};
			
		   	var $select = $('#mediaStopMark_multiSelect');
	       	$select.multiSelect({
	           selectableOptgroup: true
	       	});
	       	$select.data('multiselect').deselect_all();
	       	if($scope.mediaStop && $scope.mediaStop.stopMarks
	    		   && jQuery.isArray($scope.mediaStop.stopMarks)
	    		   && $scope.mediaStop.stopMarks.length > 0){
	    	   $select.data('multiselect').select($scope.mediaStop.stopMarks,'init');
	       	}
	       	$scope.mediaStop.stopImgs = [];
	       	if($scope.mediaStop.stopImg && $scope.mediaStop.stopImg != ''){
	       		var imgs = $scope.mediaStop.stopImg.split('|');
	       		$(imgs).each(function(index, img) {
	       			$scope.mediaStop.stopImgs.push({
	       				path: img
	       			});
	       		});
	       	}
   		},
   		removeStopImg : function(img){
        	for(var i = 0 ;i < $scope.mediaStop.stopImgs.length; i++){
        		if($scope.mediaStop.stopImgs[i].path == img.path){
        			$scope.mediaStop.stopImgs.splice(i,1);
        			return;
        		}
        	}
    	},
   		onOkClick : function() {
	    	$scope.stopMediaForm.doValidate();
	    	$scope.mediaStop.stopImg = '';
	       	if($scope.stopMediaForm.$valid) {
	       		$($scope.mediaStop.stopImgs).each(function(index, img) {
	       			$scope.mediaStop.stopImg = $scope.mediaStop.stopImg + (index == 0 ? '' : '|') + img.path;
       			});
				Page.ajaxPost('media/stop/save.do', $scope.mediaStop, function (resp) {
				    Page.notice("站点信息保存成功!");
				    $scope.stopMediaModal.hide();
				    $scope.mediaStopGrid.query();
				});
	        }
    	},
    	onHidden : function() {
        	$scope.stopMediaForm.reset();
    	},
    	setStopPoint : function(){
    		$scope.stopPointSetModal.show();
    	}
	};
	
	$scope.stopPointSetModal = {
		map : null,
		onShow : function(){
			var mapDiv = "stopPointSetModalMapDiv";
			var width = $('#' + mapDiv).width();
			var height = $('#' + mapDiv).height();
			this.map = new AMap.Map(mapDiv, {resizeEnable: true,zoom:13});
			
			this.marker = new AMap.Marker({
				position: [$scope.mediaStop.longitude || 114.296308, $scope.mediaStop.latitude || 30.595444],
				map:this.map,
				draggable: true,
		        cursor: 'move',
		        raiseOnDrag: true,
		        title:'拖动定位'
			});
			this.map.setCenter(this.marker.getPosition());
		},
		onOkClick : function() {
	    	$scope.mediaStop.longitude = this.marker.getPosition().getLng();
	    	$scope.mediaStop.latitude = this.marker.getPosition().getLat();
	    	this.hide();
    	}
	};
	
	$scope.stopMediaInfoModal = {
		setStopId : function(stopId){
			this.stopId = stopId;
			return this;
		},
		onShow : function(){
			Page.ajaxGetQuiet('media/stop/' + this.stopId + '/info.do', null, function (resp) {
				$scope.mediaStop = resp.data;
				Page.ajaxGetQuiet('media/stop/' + $scope.mediaStop.stopId + '/marks.do', null, function (resp) {
					$scope.mediaStop.marks = resp.data;
				});
				$scope.mediaStop.stopImgs = [];
		       	if($scope.mediaStop.stopImg && $scope.mediaStop.stopImg != ''){
		       		var imgs = $scope.mediaStop.stopImg.split('|');
		       		$(imgs).each(function(index, img) {
		       			$scope.mediaStop.stopImgs.push({
		       				path: img
		       			});
		       		});
		       	}
			});
			
   		}
	};
	
	$scope.stopPointsModal = {
		stops : [],
		init : function(stopData){
			this.stops = [];
			if(stopData && jQuery.isArray(stopData)){
				this.stops = stopData;
			}else if (stopData){
				this.stops.push(stopData);
			}
			return this;
		},
		onShow : function(){
			//道道通
//			if(!$scope.stopPointsModal.map){
//				setTimeout(function() {
//					var mapDiv = "stopPointsModalMapDiv";
//					var width = $('#' + mapDiv).width();
//					var height = $('#' + mapDiv).height();
//					$scope.stopPointsModal.map = new RMap(document.getElementById(mapDiv), 114.296308, 30.595444, 8, width, height);
//					$scope.stopPointsModal.map.show();
//					
//					$($scope.stopPointsModal.stops).each(function(index, stop) {
//						if(stop.longitude && stop.latitude){
//							var markContent = stop.stopName + '-(' + stop.roadName + '-' + stop.direction + ')';
//							$scope.stopPointsModal.map.addMarker(new RLabelMarker(stop.longitude,stop.latitude,markContent,'./assets/global/plugins/rmap/image/poi.png',2,2,15,20));
//						}
//					});
//					$scope.stopPointsModal.map.refresh();
//				},300);
//			}else{
//				$scope.stopPointsModal.map.removeAllMarker();
//				$($scope.stopPointsModal.stops).each(function(index, stop) {
//					if(stop.longitude && stop.latitude){
//							var markContent = stop.stopName + '-(' + stop.roadName + '-' + stop.direction + ')';
//							$scope.stopPointsModal.map.addMarker(new RLabelMarker(stop.longitude,stop.latitude,markContent,'./assets/global/plugins/rmap/image/poi.png',2,2,15,20));
//					}
//				});
//				$scope.stopPointsModal.map.refresh();
//			}
			//高德
//			var stationSearch;
//			AMap.service('AMap.StationSearch',function(){//回调函数
//					stationSearch = new AMap.StationSearch({city:'027'});
//			});
			
			var mapDiv = "stopPointsModalMapDiv";
			var width = $('#' + mapDiv).width();
			var height = $('#' + mapDiv).height();
			$scope.stopPointsModal.map = new AMap.Map(mapDiv, {resizeEnable: true,zoom:13});
			
			var markers = [];
			var infoWindow = new AMap.InfoWindow({offset:new AMap.Pixel(0,-30)});
			$($scope.stopPointsModal.stops).each(function(index, stop) {
				if(stop.longitude && stop.latitude){
					var marker = new AMap.Marker({
						position: [stop.longitude, stop.latitude],
						title:stop.stopName + '-(' + stop.roadName + '-' + stop.direction + ')',
						map:$scope.stopPointsModal.map
					});
					marker.on('click',function(e){
						infoWindow.setContent(e.target.getTitle());
						infoWindow.open($scope.stopPointsModal.map, e.target.getPosition());
					});
					markers[markers.length] = marker;
				}else{
//					  stationSearch.search(stop.stopName, function(status, result) {
//			            if (status === 'complete' && result.info === 'OK' && result.stationInfo.length > 0) {
//			              	var marker = new AMap.Marker({
//								position: result.stationInfo[0].location,
//								title:result.stationInfo[0].name,
//								map:$scope.stopPointsModal.map
//							});
//							marker.on('click',function(e){
//								infoWindow.setContent(e.target.getTitle());
//								infoWindow.open($scope.stopPointsModal.map, e.target.getPosition());
//							});
//							markers[markers.length] = marker;
//			            }
//			         });
				}
			});
			
			setTimeout(function() {
				if(markers.length > 1){
					$scope.stopPointsModal.map.setFitView();
				}else if(markers.length == 1){
					$scope.stopPointsModal.map.setCenter(markers[0].getPosition());
				}
			},300);
		}	
	};
	
	$scope.hctEquipmentGrid = {
		options : {
			lazy : true,
			bAutoWidth : false,
			paging : false
		},
		column_defs: [
			{
				target: 17,
				buttons: [
					{
						name: '编辑',
						clazz: 'btn-edit',
						icon: 'fa-edit',
						event: 'equipmentUpdate'
					},
					{
						name : '删除',
						clazz: 'btn btn-delete',
						icon: 'fa-trash-o',
						event : 'equipmentDelete'
					}
				]
			}
		],

		equipmentUpdate : function(row) {
			$scope.equipment = row;
			$scope.hctEquipmentAddModal.show();
		},
		equipmentDelete : function(row) {
			Page.confirm("确定要删除该设备记录吗？", function () {
				Page.ajaxPost('media/stop/equipmentDelete.do', row, function () {
					$scope.equipmentGrid.query();
				});
			});
		},
		addEquipment : function() {
			$scope.equipment = {};
			$scope.equipment.stopId = $scope.hctEquipmentGrid.query.stopId;
			$scope.hctEquipmentAddModal.show();
		}
	};

	$scope.zgEquipmentGrid = {
		options : {
			lazy : true,
			bAutoWidth : false,
			paging : false
		},
		column_defs: [
			{
				target: 11,
				buttons: [
					{
						name: '编辑',
						clazz: 'btn-edit',
						icon: 'fa-edit',
						event: 'equipmentUpdate'
					},
					{
						name : '删除',
						clazz: 'btn btn-delete',
						icon: 'fa-trash-o',
						event : 'equipmentDelete'
					}
				]
			}
		],

		equipmentUpdate : function(row) {
			$scope.equipment = row;
			$scope.zgEquipmentAddModal.show();
		},
		equipmentDelete : function(row) {
			Page.confirm("确定要删除该设备记录吗？", function () {
				Page.ajaxPost('media/stop/equipmentDelete.do', row, function () {
					$scope.equipmentGrid.query();
				});
			});
		},
		addEquipment : function() {
			$scope.equipment = {};
			$scope.equipment.stopId = $scope.zgEquipmentGrid.query.stopId;
			$scope.zgEquipmentAddModal.show();
		}
	};


	$scope.hctEquipmentModal = {
		onOkClick : function() {

		},
		onHidden : function() {

		}
	};

	$scope.zgEquipmentModal = {
		onOkClick : function() {

		},
		onHidden : function() {

		}
	};

	$scope.hctEquipmentAddModal = {
		onShow : function() {
			if($scope.equipment.equipmentId) {
				this.setTitle("编辑设备");
			} else {
				this.setTitle("新增设备");
			}
		},
		onOkClick : function() {
			if(!$scope.hctEquipmentAddForm.$valid) {
				$scope.hctEquipmentAddForm.doValidate();
			} else {
				if(!$scope.equipment.equipmentId) { //添加
					Page.ajaxPost('media/stop/equipmentAdd.do', $scope.equipment, function (resp) {
						$scope.hctEquipmentGrid.query();
						$scope.hctEquipmentAddModal.hide();
					});
				} else {
					Page.ajaxPost('media/stop/equipmentUpdate.do', $scope.equipment, function (resp) {
						$scope.hctEquipmentGrid.query();
						$scope.hctEquipmentAddModal.hide();
					});
				}
			}
		},
		onHidden : function() {
			$scope.hctEquipmentAddForm.reset();
		}
	};

	$scope.zgEquipmentAddModal = {
		onShow : function() {
			if($scope.equipment.equipmentId) {
				this.setTitle("编辑设备");
			} else {
				this.setTitle("新增设备");
			}
		},
		onOkClick : function() {
			if(!$scope.zgEquipmentAddForm.$valid) {
				$scope.zgEquipmentAddForm.doValidate();
			} else {
				if(!$scope.equipment.equipmentId) { //添加
					Page.ajaxPost('media/stop/equipmentAdd.do', $scope.equipment, function (resp) {
						$scope.zgEquipmentGrid.query();
						$scope.zgEquipmentAddModal.hide();
					});
				} else {
					Page.ajaxPost('media/stop/equipmentUpdate.do', $scope.equipment, function (resp) {
						$scope.zgEquipmentGrid.query();
						$scope.zgEquipmentAddModal.hide();
					});
				}
			}
		},
		onHidden : function() {
			$scope.zgEquipmentAddForm.reset();
		}
	};
	
	$scope.stopResourcesModal = {
		onShow : function(){
			this.setTitle('站点资源列表 - ' + $scope.mediaStop.stopName);
			$($scope.mediaTypes).each(function(index, media) {
				  if(!media.items){
					  Page.ajaxPostQuiet('mediaType/' + media.mediaId + '/items.do', null, function (resp) {
						  media.items = resp.data;
					  });
				  }
			});
			this.query();
		},
		query : function(){
			$scope.mediaStop.resources = [];
			Page.ajaxGetQuiet('media/resource/list/stop/' + $scope.mediaStop.stopId + '.do' , null, function (resp) {
				$scope.mediaStop.resources = resp.data;
			});
		},
		toAdd : function(media){
			$scope.stopResourceEditModal.initConfig(media).show();
		},
		toEdit : function(row, media){
			$scope.stopResourceEditModal.initConfig(media).initResource(row).show();
		},
		remove : function(row){
			Page.confirm('确认废除该媒体资源?', function(){
				Page.ajaxPost('media/resource/' + row.resourceId + '/remove.do', null, function (resp) {
					$scope.stopResourcesModal.query();
				});
			});
		},
		revert : function(row){
			Page.confirm('确认恢复该媒体资源?', function(){
				Page.ajaxPost('media/resource/'+ row.resourceId +'/revert.do', null, function (resp) {
						$scope.stopResourcesModal.query();
				});
			});
		},
		view : function(row){
			$scope.browsePicture(row.resourceImg);
		}
	};
	
	$scope.stopResourceEditModal = {
		media : {},
		resource : {},
		initConfig : function(media){
			this.media = media;
			return this;
		},
		initResource : function(resource){
			this.resource = angular.copy(resource);
			return this;
		},
		onShow : function(){
			this.setTitle('站点媒体资源编辑 - ' + this.media.mediaName);
			
			this.resource.stopId = $scope.mediaStop.stopId;
			this.resource.mediaType = this.media.mediaId;
			this.resource.file = {
				path: this.resource.resourceImg
			};
		},
		onOkClick : function() {
	    	$scope.resourceForm.doValidate();
	       	if($scope.resourceForm.$valid) {
	       		this.resource.resourceImg = this.resource.file.path;
	       		Page.ajaxPost('media/resource/save.do', this.resource, function (resp) {
				   	$scope.stopResourceEditModal.hide();
				   	$scope.stopResourcesModal.query();
				});
	        }
    	},
    	onHidden : function() {
        	$scope.resourceForm.reset();
    	}
	};

}]);


